import axios from 'axios';
import { ApiResponse, NotificationData, UserData, LoginResponse, CreateTestNotificationResponse, FileItem, FolderItem, StorageStats, ShareLinkResponse } from '../types/api';

const API_BASE_URL = process.env.REACT_APP_API_URL || 'http://localhost:3002/api';

// 创建axios实例
const apiClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: 300000, // 增加到300秒，特别是为了AI分析
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
apiClient.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    const url = config.url || '';
    
    // 为需要认证的请求添加token，但排除注册和登录相关请求
    if (token && !url.includes('/user/account') && !url.includes('/auth/login') && !url.includes('/auth/register') && !url.includes('/auth/send-login-code') && !url.includes('/auth/login-with-code')) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
apiClient.interceptors.response.use(
  (response) => {
    // console.log('API响应:', response.config.url, response.data); // 注释掉以减少控制台输出
    // 对于blob响应，返回完整的response对象
    if (response.config.responseType === 'blob') {
      return response;
    }
    return response.data;
  },
  (error) => {
    console.error('API错误:', error.config?.url, error.response?.data || error.message);
    
    // 处理网络错误
    if (!error.response) {
      console.error('网络错误:', error.message);
      return Promise.reject({
        message: '网络连接失败，请检查网络设置',
        isNetworkError: true
      });
    }
    
    // 处理401认证错误
    if (error.response?.status === 401) {
      const url = error.config?.url || '';
      
      // 只有在非认证相关请求时才重定向到登录页面
      if (!url.includes('/user/account') && 
          !url.includes('/auth/login') && 
          !url.includes('/auth/register') && 
          !url.includes('/auth/send-login-code') && 
          !url.includes('/auth/login-with-code') &&
          !url.includes('/auth/verify')) {
        // 延迟清除token，避免在验证过程中误清除
        setTimeout(() => {
          localStorage.removeItem('token');
          window.location.href = '/login';
        }, 100);
      }
    }
    
    // 处理超时错误
    if (error.code === 'ECONNABORTED') {
      return Promise.reject({
        message: '请求超时，请稍后重试',
        isTimeoutError: true
      });
    }
    
    return Promise.reject(error.response?.data || error);
  }
);

export const authService = {
  // 用户注册
  register: async (userData: {
    username: string;
    email: string;
    password: string;
  }) => {
    return apiClient.post('/auth/register', userData);
  },

  // 验证邮箱
  verifyEmail: async (email: string, code: string) => {
    return apiClient.post('/auth/verify-email', { email, code });
  },

  // 用户登录
  login: async (login: string, password: string) => {
    return apiClient.post('/auth/login', { login, password });
  },

  // 验证码登录
  loginWithCode: async (email: string, code: string) => {
    return apiClient.post('/auth/login-with-code', { email, code });
  },

  // 发送登录验证码
  sendLoginCode: async (email: string) => {
    return apiClient.post('/auth/send-login-code', { email });
  },

  // 验证token
  verifyToken: async (token: string) => {
    return apiClient.get('/auth/verify', {
      headers: { Authorization: `Bearer ${token}` }
    });
  }
};

export const userService = {
  // 获取用户信息
  getProfile: async () => {
    return apiClient.get('/user/profile');
  },

  // 创建用户账号（新用户注册）
  createAccount: async (accountData: { email: string; username: string; password: string }) => {
    return apiClient.post('/user/account', accountData);
  },

  // 更新用户信息
  updateProfile: async (userData: any) => {
    return apiClient.put('/user/profile', userData);
  },

  // 上传头像
  uploadAvatar: async (file: File) => {
    const formData = new FormData();
    formData.append('avatar', file);
    return apiClient.post('/user/avatar', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
  }
};

export const focusService = {
  // 获取专注设置
  getSettings: async () => {
    return apiClient.get('/focus/settings');
  },

  // 更新专注设置
  updateSettings: async (settings: any) => {
    return apiClient.put('/focus/settings', settings);
  },

  // 获取计时器列表
  getTimers: async () => {
    return apiClient.get('/focus/timers');
  },

  // 创建计时器
  createTimer: async (timerData: any) => {
    return apiClient.post('/focus/timers', timerData);
  },

  // 更新计时器
  updateTimer: async (timerId: number, timerData: any) => {
    return apiClient.put(`/focus/timers/${timerId}`, timerData);
  },

  // 删除计时器
  deleteTimer: async (timerId: number) => {
    return apiClient.delete(`/focus/timers/${timerId}`);
  },

  // 开始专注会话
  startSession: async (sessionData: any) => {
    return apiClient.post('/focus/sessions/start', sessionData);
  },

  // 完成专注会话
  completeSession: async (sessionId: number) => {
    return apiClient.post(`/focus/sessions/${sessionId}/complete`);
  },

  // 获取专注会话列表
  getSessions: async (params?: { page?: number; limit?: number }) => {
    return apiClient.get('/focus/sessions', { params });
  }
};


export const friendService = {
  // 获取好友列表
  getFriends: async () => {
    return apiClient.get('/friend/list');
  },

  // 添加好友
  addFriend: async (friendData: any) => {
    return apiClient.post('/friend/add', friendData);
  }
};


export const aiService = {
  // 获取对话列表
  getConversations: async () => {
    return apiClient.get('/ai/conversations');
  },

  // 获取对话消息
  getMessages: async (conversationId: number) => {
    return apiClient.get(`/ai/conversations/${conversationId}/messages`);
  },

  // 创建新对话
  createConversation: async (title?: string) => {
    return apiClient.post('/ai/conversations', { title });
  },

  // 发送消息
  sendMessage: async (conversationId: number, content: string) => {
    return apiClient.post(`/ai/conversations/${conversationId}/messages`, { content });
  },

  // 删除对话
  deleteConversation: async (conversationId: number) => {
    return apiClient.delete(`/ai/conversations/${conversationId}`);
  },

  // 导出对话
  exportConversation: async (conversationId: number) => {
    return apiClient.get(`/ai/conversations/${conversationId}/export`, {
      responseType: 'text'
    });
  },

  // 更新对话标题
  updateConversationTitle: async (conversationId: number, title: string) => {
    return apiClient.put(`/ai/conversations/${conversationId}`, { title });
  },

  // 生成对话标题
  generateTitle: async (prompt: string) => {
    return apiClient.post('/ai/generate-title', { prompt });
  },

  // 获取推荐问题
  getSuggestions: async () => {
    return apiClient.get('/ai/suggestions');
  },

  // 获取智能建议问题（基于对话内容）
  getSmartSuggestions: async (conversationId: number) => {
    return apiClient.get(`/ai/suggestions/${conversationId}`);
  },

  // 获取云盘文件内容信息（用于AI分析）
  getCloudFileContents: async (limit: number = 10) => {
    return apiClient.get(`/ai/cloud-files/contents?limit=${limit}`);
  }
};



export const studyService = {
  // 获取学习计划列表
  getPlans: async () => {
    return apiClient.get('/study/plans');
  },

  // 创建学习计划
  createPlan: async (planData: any) => {
    return apiClient.post('/study/plans', planData);
  },

  // 更新学习计划
  updatePlan: async (planId: string, planData: any) => {
    return apiClient.put(`/study/plans/${planId}`, planData);
  },

  // 删除学习计划
  deletePlan: async (planId: string) => {
    return apiClient.delete(`/study/plans/${planId}`);
  },

  // 获取学习计划的任务列表
  getTasks: async (planId: string) => {
    return apiClient.get(`/study/plans/${planId}/tasks`);
  },

  // 添加学习任务
  createTask: async (planId: string, taskData: any) => {
    return apiClient.post(`/study/plans/${planId}/tasks`, taskData);
  },

  // 更新学习任务
  updateTask: async (taskId: string, taskData: any) => {
    return apiClient.put(`/study/tasks/${taskId}`, taskData);
  },

  // 删除学习任务
  deleteTask: async (taskId: string) => {
    return apiClient.delete(`/study/tasks/${taskId}`);
  },

  // 记录学习进度
  recordProgress: async (progressData: any) => {
    return apiClient.post('/study/progress', progressData);
  }
};

export const friendsService = {
  // 获取好友列表
  getFriends: async () => {
    return apiClient.get('/friends');
  },

  // 搜索用户
  searchUsers: async (query: string) => {
    return apiClient.get(`/friends/search?q=${encodeURIComponent(query)}`);
  },

  // 发送好友请求
  sendFriendRequest: async (friendId: number) => {
    return apiClient.post('/friends/request', { friend_id: friendId });
  },

  // 获取好友请求列表
  getFriendRequests: async () => {
    return apiClient.get('/friends/requests');
  },

  // 处理好友请求
  handleFriendRequest: async (requestId: number, action: 'accept' | 'reject') => {
    return apiClient.put(`/friends/requests/${requestId}`, { action });
  },

  // 删除好友
  deleteFriend: async (friendId: number) => {
    return apiClient.delete(`/friends/${friendId}`);
  },

  // 屏蔽用户
  blockUser: async (friendId: number) => {
    return apiClient.post('/friends/block', { friend_id: friendId });
  },

  // 更新在线状态
  updateOnlineStatus: async (isOnline: boolean) => {
    return apiClient.post('/friends/online-status', { is_online: isOnline });
  }
};


export const chatService = {
  // 获取聊天室列表
  getRooms: async () => {
    return apiClient.get('/chat/rooms');
  },

  // 创建私聊
  createPrivateChat: async (friendId: number) => {
    return apiClient.post('/chat/private', { friend_id: friendId });
  },

  // 创建群聊
  createGroupChat: async (name: string, description: string, memberIds: number[]) => {
    return apiClient.post('/chat/group', { 
      name, 
      description, 
      member_ids: memberIds 
    });
  },

  // 获取聊天室成员
  getRoomMembers: async (roomId: number) => {
    return apiClient.get(`/chat/rooms/${roomId}/members`);
  },

  // 获取聊天消息
  getMessages: async (roomId: number, page: number = 1, limit: number = 50) => {
    return apiClient.get(`/chat/rooms/${roomId}/messages?page=${page}&limit=${limit}`);
  },

  // 发送消息
  sendMessage: async (roomId: number, content: string, messageType: string = 'text', replyTo?: number) => {
    return apiClient.post(`/chat/rooms/${roomId}/messages`, {
      content,
      message_type: messageType,
      reply_to: replyTo
    });
  },

  // 发送文件
  sendFile: async (roomId: number, formData: FormData) => {
    return apiClient.post(`/chat/rooms/${roomId}/messages/file`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
  },

  // 删除消息
  deleteMessage: async (messageId: number) => {
    return apiClient.delete(`/chat/messages/${messageId}`);
  },

  // 添加群聊成员
  addRoomMembers: async (roomId: number, userIds: number[]) => {
    return apiClient.post(`/chat/rooms/${roomId}/members`, { user_ids: userIds });
  },

  // 移除群聊成员
  removeRoomMember: async (roomId: number, memberId: number) => {
    return apiClient.delete(`/chat/rooms/${roomId}/members/${memberId}`);
  },

  // 删除聊天室
  deleteRoom: async (roomId: number) => {
    return apiClient.delete(`/chat/rooms/${roomId}`);
  }
};


// 激励内容服务
export const motivationService = {
  // 获取激励内容
  getContent: async (type?: 'text' | 'emoji') => {
    const params = type ? { type } : {};
    return apiClient.get('/motivation/content', { params });
  },

  // 添加激励内容
  addContent: async (contentType: 'text' | 'emoji', content: string, sortOrder: number = 0) => {
    return apiClient.post('/motivation/content', {
      content_type: contentType,
      content,
      sort_order: sortOrder
    });
  },

  // 更新激励内容
  updateContent: async (id: number, data: {
    content_type?: 'text' | 'emoji';
    content?: string;
    sort_order?: number;
    is_active?: boolean;
  }) => {
    return apiClient.put(`/motivation/content/${id}`, data);
  },

  // 删除激励内容
  deleteContent: async (id: number) => {
    return apiClient.delete(`/motivation/content/${id}`);
  }
};

// 统计服务
export const statisticsService = {
  // 获取今日统计
  getTodayStats: async () => {
    return apiClient.get('/statistics/today');
  },

  // 获取历史统计
  getHistoryStats: async (days: number = 30) => {
    return apiClient.get('/statistics/history', { params: { days } });
  },

  // 获取用户成就
  getAchievements: async () => {
    return apiClient.get('/statistics/achievements');
  },

  // 获取学习目标
  getGoals: async (type: string = 'all') => {
    return apiClient.get('/statistics/goals', { params: { type } });
  },

  // 获取学习习惯
  getHabits: async () => {
    return apiClient.get('/statistics/habits');
  },

  // 更新统计数据
  updateStats: async (type: string, value: number = 1, duration: number = 0, points: number = 0) => {
    return apiClient.post('/statistics/update', {
      type,
      value,
      duration,
      points
    });
  }
};

export const careerService = {
  // 获取职业匹配推荐
  getMatches: async (limit: number = 20) => {
    return apiClient.get(`/career/matches?limit=${limit}`);
  },

  // 获取职业列表
  getCareers: async (page: number = 1, limit: number = 20, category?: string, search?: string) => {
    const params = new URLSearchParams({
      page: page.toString(),
      limit: limit.toString()
    });
    
    if (category) params.append('category', category);
    if (search) params.append('search', search);
    
    return apiClient.get(`/career/careers?${params.toString()}`);
  },

  // 获取职业分类
  getCategories: async () => {
    return apiClient.get('/career/categories');
  },

  // 生成试炼题目
  generateQuestion: async (careerId: number) => {
    return apiClient.post('/career/trial/question', { careerId });
  },

  // 评测答案
  evaluateAnswer: async (careerId: number, question: string, answer: string) => {
    return apiClient.post('/career/trial/evaluate', { careerId, question, answer });
  }
};

export const knowledgeGraphService = {
  // 分析文件内容
  analyzeFiles: async () => {
    return apiClient.post('/knowledge-graph/analyze');
  },

  // 构建知识图谱
  buildGraph: async () => {
    return apiClient.post('/knowledge-graph/build');
  },

  // 获取知识图谱数据
  getGraph: async () => {
    return apiClient.get('/knowledge-graph/graph');
  },

  // 获取文件关联详情
  getFileRelationships: async (fileId: number) => {
    return apiClient.get(`/knowledge-graph/file/${fileId}/relationships`);
  }
};

// 通知服务
export const notificationService = {
  // 获取通知列表
  getNotifications: async (): Promise<ApiResponse<NotificationData[]>> => {
    return apiClient.get('/notification/list');
  },

  // 标记通知为已读
  markAsRead: async (id: number): Promise<ApiResponse> => {
    return apiClient.put(`/notification/read/${id}`);
  },

  // 创建通知
  createNotification: async (notification: {
    title: string;
    content: string;
    type?: string;
  }): Promise<ApiResponse> => {
    return apiClient.post('/notification/create', notification);
  },

  // 删除通知
  deleteNotification: async (id: number): Promise<ApiResponse> => {
    return apiClient.delete(`/notification/${id}`);
  },

  // 获取未读通知数量
  getUnreadCount: async (): Promise<ApiResponse<{ count: number }>> => {
    return apiClient.get('/notification/unread-count');
  },

  // 创建测试通知
  createTestNotification: async (): Promise<ApiResponse> => {
    return apiClient.post('/notification/create-test');
  },

  // 全部标记为已读
  markAllAsRead: async (): Promise<ApiResponse> => {
    return apiClient.put('/notification/mark-all-read');
  },

  // 全部删除
  deleteAll: async (): Promise<ApiResponse> => {
    return apiClient.delete('/notification/delete-all');
  },

  // 获取通知详情
  getNotificationDetail: async (id: number): Promise<ApiResponse<NotificationData>> => {
    return apiClient.get(`/notification/${id}`);
  },
};

// 云盘存储服务
export const cloudStorageService = {
  // 初始化云盘存储
  init: async (): Promise<ApiResponse> => {
    return apiClient.get('/cloud-storage/init');
  },

  // 获取存储统计信息
  getStats: async (): Promise<ApiResponse & StorageStats> => {
    return apiClient.get('/cloud-storage/stats');
  },

  // 创建文件夹
  createFolder: async (folderName: string, parentId?: number): Promise<ApiResponse> => {
    return apiClient.post('/cloud-storage/folders', { folderName, parentId });
  },

  // 获取文件夹列表
  getFolders: async (parentId?: number): Promise<ApiResponse & {folders: FolderItem[]}> => {
    return apiClient.get(`/cloud-storage/folders?parentId=${parentId || ''}`);
  },

  // 重命名文件夹
  renameFolder: async (folderId: number, folderName: string): Promise<ApiResponse> => {
    return apiClient.put(`/cloud-storage/folders/${folderId}`, { folderName });
  },

  // 删除文件夹
  deleteFolder: async (folderId: number): Promise<ApiResponse> => {
    return apiClient.delete(`/cloud-storage/folders/${folderId}`);
  },

  // 上传文件
  uploadFile: async (formData: FormData): Promise<ApiResponse> => {
    console.log('API调用 - 上传文件:', formData);
    try {
      const response = await apiClient.post('/cloud-storage/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });
      console.log('API响应 - 上传文件:', response);
      return response as unknown as ApiResponse;
    } catch (error) {
      console.error('API错误 - 上传文件:', error);
      throw error;
    }
  },

  // 获取文件列表
  getFiles: async (folderId?: number, page: number = 1, limit: number = 20): Promise<ApiResponse & {files: FileItem[]}> => {
    return apiClient.get(`/cloud-storage/files?folderId=${folderId || ''}&page=${page}&limit=${limit}`);
  },

  // 下载文件
  downloadFile: async (fileId: number) => {
    return apiClient.get(`/cloud-storage/download/${fileId}`, {
      responseType: 'blob',
    });
  },

  // 删除文件
  deleteFile: async (fileId: number): Promise<ApiResponse> => {
    return apiClient.delete(`/cloud-storage/files/${fileId}`);
  },

  // 重命名文件
  renameFile: async (fileId: number, newName: string): Promise<ApiResponse> => {
    return apiClient.put(`/cloud-storage/files/${fileId}/rename`, { newName });
  },

  // 移动文件
  moveFile: async (fileId: number, newFolderId?: number): Promise<ApiResponse> => {
    return apiClient.put(`/cloud-storage/files/${fileId}/move`, { newFolderId });
  },

  // 创建文件分享链接
  createShare: async (fileId: number, shareType: string = 'private', password?: string, expiresAt?: string): Promise<ShareLinkResponse> => {
    return apiClient.post(`/cloud-storage/files/${fileId}/share`, {
      shareType,
      password,
      expiresAt
    });
  },

  // 获取分享文件信息
  getShareInfo: async (shareToken: string): Promise<ApiResponse> => {
    return apiClient.get(`/cloud-storage/share/${shareToken}`);
  },

  // 验证分享密码
  verifySharePassword: async (shareToken: string, password: string): Promise<ApiResponse> => {
    return apiClient.post(`/cloud-storage/share/${shareToken}/verify`, { password });
  },

  // 获取文件操作日志
  getLogs: async (page: number = 1, limit: number = 20): Promise<ApiResponse> => {
    return apiClient.get(`/cloud-storage/logs?page=${page}&limit=${limit}`);
  }
};

export default apiClient;